package cn.chencaiju.day13;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

//创建服务器，接受请求
public class Server {
	public static void main(String[] args) {
		ServerSocket server=null;
		Socket socket=null;
		InputStream in=null;
		try {
			//1024以上端口
			server=new ServerSocket(10086);
			System.out.println("等待连接！");
			//一直等待客户端连接
			socket=server.accept();
			System.out.println("有新的连接！");
			
			//开始通信
			Thread t=new Thread(new ClientThread(socket));
			t.start();
			t.join();
			
			System.out.println("通信结束。。。。");
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			Utils.closeQuietly(in);
			Utils.closeQuietly(socket);
			Utils.closeQuietly(server);
		}
	}
}
//异步线程,宏观上同步通信
class ClientThread implements Runnable{
	private InputStream in;
	private Socket socket;
	
	public ClientThread(Socket socket) {
		super();
		this.socket = socket;
	}

	@Override
	public void run() {
		try {
			in=socket.getInputStream();
			while(true) {
				char read=(char) (in.read());
				System.out.print(read);
				if(read=='8') {
					break;
				}
			}				
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			Utils.closeQuietly(in);
			Utils.closeQuietly(socket);
		}
	}
	
}